package com.hxb.maildemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;

/**
 * @author HXB
 * @Title:
 * @Description:
 * @date 2020-11-11 16:58
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    /**
     * 简单邮件测试
     * @param email
     */
    @Override
    public void sendSimple(String email){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("email测试");
        message.setText("邮件测试内容");
        message.setTo(email);
        message.setFrom("1219382277@qq.com");
        javaMailSender.send(message);
    }

    /**
     * 复杂邮件测试
     * @param email
     * @throws MessagingException
     */
    @Override
    public void sendComplicated(String email) throws MessagingException {
        //创建一个复杂的消息邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //用MimeMessageHelper来包装MimeMessage
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
        mimeMessageHelper.setSubject("email测试");
        mimeMessageHelper.setText("邮件测试内容");
        mimeMessageHelper.setTo(email);
        mimeMessageHelper.setFrom("1219382277@qq.com");
        mimeMessageHelper.addAttachment("meinv.jpg",new File("D:\\meinv.jpg"));
        javaMailSender.send(mimeMessage);

    }

    @Async("taskExecutor")
    @Override
    public void sendemail(String subject, String from, String touserEmail, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(subject);
        message.setFrom(from);
        message.setTo(touserEmail);
        message.setSentDate(new Date());
        message.setText(text);
        javaMailSender.send(message);
    }
}
